package cn.myjerry.test.javassist;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtMethod;

/**
 * 测试使用javassist生成一个类
 * @author Jerry
 *
 */
public class Demo01 {
	public static void main(String[] args) throws Exception {
		ClassPool pool = ClassPool.getDefault();
		CtClass cc = pool.makeClass("cn.myjerry.test.javassist.bean.Emp");
		
		// 创建属性
		CtField sf1 = CtField.make("private int No;", cc);
		CtField sf2 = CtField.make("private String Name;", cc);
		cc.addField(sf1);
		cc.addField(sf2);
		
		// 创建方法
		CtMethod cm1 = CtMethod.make("public int getNo(){return No;}", cc);
		CtMethod cm2 = CtMethod.make("public void setNo(int no){this.No = no;}", cc);
		cc.addMethod(cm1);
		cc.addMethod(cm2);
		
		// 添加构造器
		CtConstructor constructor = new CtConstructor(new CtClass[] {CtClass.intType, pool.get("java.lang.String")}, cc);
		constructor.setBody("{ this.No = No; this.Name = Name; }");
		cc.addConstructor(constructor);
		
		cc.writeFile("/Users/zpon/workspace/java/testjava03/src");	// 将上面构造好的类写出
		System.out.println("生成类，成功");
	}
}
